package org.biodas.jdas.client;

import org.biodas.jdas.client.adapters.sequence.DasSequenceAdapter;
import org.biodas.jdas.exceptions.DASClientException;
import org.biodas.jdas.schema.sequence.DASSEQUENCE;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

public class SequenceClient implements SequenceClientInterface  {
	/**
	 * Retrieves a sequence response.
	 * @param serverURL
	 * @param arguments
	 */
	private DasSequenceAdapter fetchData(String serverURL, String arguments) throws DASClientException {
        JAXBContext jc;
        try {
            if (!serverURL.endsWith("/")) {
                serverURL += "/";
            }
			jc = JAXBContext.newInstance("org.biodas.jdas.schema.sequence");
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            String url = serverURL + "/sequence" + arguments;
			return new DasSequenceAdapter((DASSEQUENCE) unmarshaller.unmarshal(new URL(url)));
		} catch (MalformedURLException e) {
			throw new DASClientException(e.getMessage(), e.getCause());
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			throw new DASClientException(e.getMessage(), e.getCause());
		}
	}

	/* (non-Javadoc)
	 * @see org.biodas.jdas.client.SequenceClientInterface#fetchData(java.lang.String, java.util.List)
	 */
	@Override
	public DasSequenceAdapter fetchData(String serverURL, List<String> segments) throws DASClientException {
        String arguments = "";
        String segmentArguments = null;
        if ((segments != null) && (segments.size() != 0)) {
            segmentArguments= "";
            for (String segment: segments) {
                segmentArguments += ";segment=" + segment;
            }
            segmentArguments = segmentArguments.substring(1); //we need to remove the first ;
        }
        if (segmentArguments != null) {
            arguments = arguments + "?" + segmentArguments;
        } 
        return this.fetchData(serverURL, arguments);
	}
}
